#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "ThreadPool.hpp"
#include "InetAddr.hpp"
#include "UdpServer.hpp"
#include "Comm.hpp"

using namespace std;

void Usage(string proc)
{
    cout << "Usage: " << proc << " + ip + port" << endl;
}
int InitClient(string &serverip, uint16_t serverport, struct sockaddr_in *server)
{
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        cout << "sock create fail" << endl;
    }

    // 填充结构体字段
    memset(server, 0, sizeof(struct sockaddr_in));
    server->sin_family = AF_INET;
    server->sin_port = htons(serverport);
    server->sin_addr.s_addr = inet_addr(serverip.c_str());

    return sockfd;
}
void recvmessage(int sockfd, string &name)
{
    int fd = OpenDev("/dev/pts/2", O_WRONLY);
    while(true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
        if(n > 0)
        {
            buffer[n] = 0;
            write(fd, buffer, strlen(buffer));
        }
    }
}
void sendmessage(int sockfd, struct sockaddr_in &serveraddr, string &name)
{
    string message;
    while(true)
    {
        printf("%s | Enter# ", name.c_str());
        fflush(stdout);
        getline(cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
    }
}
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(4);
    }
    uint16_t serverport = stoi(argv[2]);
    string serverip = argv[1];

    struct sockaddr_in serveraddr;
    int sockfd = InitClient(serverip, serverport, &serveraddr);
    if(sockfd < 0) return -1;

    func_t r = bind(&recvmessage, sockfd, placeholders::_1);
    func_t s = bind(&sendmessage, sockfd, serveraddr, placeholders::_1);

    Thread Recver(r, "recver"); // 收
    Thread Sender(s, "sender"); // 发

    Recver.Start();
    Sender.Start();

    Recver.Join();
    Sender.Join();

    return 0;
}